package mi.payment.ui.base;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import java.math.BigDecimal;

import mi.payment.R;
import mi.payment.utils.MToast;
import sunmi.sunmiui.utils.LogUtil;

/**
 * Author   : huangyi
 * Date     : 2017/03/09
 * Email    : huangyi@sunmi.com
 * Function : 计算器
 */

public class CalculatorActivity extends ParentActivity {

    private static final String TAG = "CalculatorActivity";

    private NumberKeyCalculator mKeyboard;
    private TextView tvResult;

    private String mLeft = "";
    private String mRight = "";
    private Double mLNumber = 0.00;
    private Double mRNumber = 0.00;
    private int calType = 0;                    //运算类型

    private ImageView ivBack;                   //返回按钮

    private boolean isAdd, isSub, isMul, isDiv; //是否进行运算
    private boolean isClickResult = false;      //是否已经运算过

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStatusBarColor(R.color.color_111111);
        setContentView(R.layout.activity_calculator);
        initView();
        setCallBack();
    }

    /**
     * 初始View
     */
    private void initView() {
        mKeyboard = (NumberKeyCalculator) findViewById(R.id.keyboard);
        tvResult = (TextView) findViewById(R.id.tv_calculator_result);
        ivBack = (ImageView) findViewById(R.id.iv_back);
    }

    /**
     * 设置回调监听事件
     */
    private void setCallBack() {
        mKeyboard.setKeyClickCallback(new NumberKeyCalculator.KeyClickCallback() {
            @Override
            public void onAdd() {//+
                calType = 1;
            }

            @Override
            public void onSubtract() {//-
                calType = 2;
            }

            @Override
            public void onMultiply() {//*
                calType = 3;
            }

            @Override
            public void onDivide() {//÷
                calType = 4;
            }

            @Override
            public void onNumClick(int keyNum) {
                isClickResult = false;
                if((mLeft.length() == 7&&!mLeft.contains(".")) || (mRight.length() == 7&&!mRight.contains("."))){
                    return;
                }
                if (calType == 0) {
                    if (mLeft.equals("0.00")) {
                        mLeft = "0";
                    }
                    if (doubleDecimal(mLeft)) {
                        return;
                    }
                    if (mLeft.equals("") && keyNum == 0) {
                        return;
                    }
                    if (mLeft.equals("0")) {
                        mLeft = "";
                    }
                    mLeft += keyNum;
                    tvResult.setText(mLeft);
                } else {
                    if (doubleDecimal(mRight)) {
                        return;
                    }
                    if (mRight.equals("") && keyNum == 0) {
                        tvResult.setText("0");
                        return;
                    }
                    mRight += keyNum;
                    tvResult.setText(mRight);
                }
                cleanCal();
            }

            @Override
            public void onDelClick() {
                //如果是两个数的运算结果，直接清0
                if (isClickResult) {
                    clean();
                    tvResult.setText("0");
                } else {
                    if (calType == 0) {
                        if (!TextUtils.isEmpty(mLeft) && mLeft.length() > 1) {
                            mLeft = mLeft.substring(0, mLeft.length() - 1);
                            tvResult.setText(mLeft);
                        } else {
                            tvResult.setText("0");
                            mLeft = "";
                        }
                    } else {
                        if (!TextUtils.isEmpty(mRight) && mRight.length() > 1) {
                            mRight = mRight.substring(0, mRight.length() - 1);
                            tvResult.setText(mRight);
                        } else {
                            tvResult.setText("0");
                            mRight = "";
                        }
                    }
                }
            }

            @Override
            public void onCleanClick() {
                tvResult.setText("0");
                clean();
            }

            @Override
            public void onCalResult() {
                isClickResult = true;
                if (calType == 1) {
                    addResult();
                } else if (calType == 2) {
                    subResult();
                } else if (calType == 3) {
                    mulResult();
                } else if (calType == 4) {
                    divResult();
                }
                calType = 0;
            }

            @Override
            public void onDecimalPoint() {
                if (calType == 0) {
                    if (!mLeft.contains(".")) {
                        if (tvResult.getText().equals("0")) {
                            mLeft = "0.";
                        } else {
                            mLeft += ".";
                        }
                    }else{
                        if(mLeft.length() == 10){
                            return;
                        }
                    }
                    tvResult.setText(mLeft);
                } else {
                    if (!mRight.contains(".")) {
                        if (mRight.equals("")) {
                            mRight += "0.";
                        } else {
                            mRight += ".";
                        }
                    }else{
                        if(mRight.length() == 10){
                            return;
                        }
                    }
                    tvResult.setText(mRight);
                }
            }

            @Override
            public void onConfirm() {
                setResultCallBack();
            }
        });
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    /**
     * 允许输入的最大小数位为2
     */
    private boolean doubleDecimal(String str) {
        if (str.contains(".")) {
            int index = str.indexOf(".");
            String subStr = str.substring(index, str.length());
            if (subStr.length() == 3) {
                return true;
            }
        }
        return false;
    }

    /**
     * 将计算结果回传到上一个Activity
     */
    private void setResultCallBack() {
        Intent intent = getIntent();
        intent.putExtra("result", tvResult.getText().toString());
        setResult(2, intent);
        finish();
    }

    /**
     * 清空运算标识
     */
    private void cleanCal() {
        isAdd = false;
        isSub = false;
        isMul = false;
        isDiv = false;
    }

    private void addResult() {
        if (!isAdd) {
            parseDouble();
            tvResult.setText(add(mLNumber, mRNumber));
            macClean();
            isAdd = true;
            isSub = false;
            isMul = false;
            isDiv = false;
        }
    }

    private void subResult() {
        if (!isSub) {
            parseDouble();
            tvResult.setText(sub(mLNumber, mRNumber));
            macClean();
            isSub = true;
            isAdd = false;
            isMul = false;
            isDiv = false;
        }
    }

    private void mulResult() {
        if (!isMul) {
            parseDouble();
            tvResult.setText(mul(mLNumber, mRNumber));
            macClean();
            isMul = true;
            isAdd = false;
            isSub = false;
            isDiv = false;
        }
    }

    private void divResult() {
        if (!isDiv) {
            try {
                parseDouble();
                if (mRNumber == 0) {
                    clean();
                    MToast.showToast(R.string.divisior_hint);
                    tvResult.setText("0");
                    return;
                }
                tvResult.setText(div(mLNumber, mRNumber, 2));
                macClean();
                isDiv = true;
                isAdd = false;
                isSub = false;
                isMul = false;
            } catch (IllegalAccessException e) {
                e.printStackTrace();
                LogUtil.e(TAG, e.getMessage());
            }
        }
    }

    private void parseDouble() {
        if (!mLeft.equals("") && !mRight.equals("")) {
            mLNumber = Double.parseDouble(mLeft);
            mRNumber = Double.parseDouble(mRight);
        }
    }

    /**
     * 清空数据
     */
    private void clean() {
        mLeft = "";
        mRight = "";
        mLNumber = 0.00;
        mRNumber = 0.00;
        calType = 0;
    }

    /**
     * 清空右边的数据
     */
    private void macClean() {
        mLeft = tvResult.getText().toString();
        mRight = "";
        mRNumber = 0.00;
    }

    /**
     * 提供精确加法计算的add方法
     *
     * @param value1 被加数
     * @param value2 加数
     * @return 两个参数的和
     */
    public String add(double value1, double value2) {
        BigDecimal b1 = new BigDecimal(Double.valueOf(value1));
        BigDecimal b2 = new BigDecimal(Double.valueOf(value2));
        return b1.add(b2).setScale(2, BigDecimal.ROUND_HALF_EVEN).toString();
    }

    /**
     * 提供精确减法运算的sub方法
     *
     * @param value1 被减数
     * @param value2 减数
     * @return 两个参数的差
     */
    public String sub(double value1, double value2) {
        BigDecimal b1 = new BigDecimal(Double.valueOf(value1));
        BigDecimal b2 = new BigDecimal(Double.valueOf(value2));
        return b1.subtract(b2).setScale(2, BigDecimal.ROUND_HALF_EVEN).toString();
    }

    /**
     * 提供精确乘法运算的mul方法
     *
     * @param value1 被乘数
     * @param value2 乘数
     * @return 两个参数的积
     */
    public String mul(double value1, double value2) {
        BigDecimal b1 = new BigDecimal(Double.valueOf(value1));
        BigDecimal b2 = new BigDecimal(Double.valueOf(value2));
        return b1.multiply(b2).setScale(2, BigDecimal.ROUND_HALF_EVEN).toString();
    }

    /**
     * 提供精确的除法运算方法div
     *
     * @param value1 被除数
     * @param value2 除数
     * @param scale  精确范围
     * @return 两个参数的商
     * @throws IllegalAccessException
     */
    public String div(double value1, double value2, int scale) throws IllegalAccessException {
        //如果精确范围小于0，抛出异常信息
        if (scale < 0) {
            throw new IllegalAccessException("精确度不能小于0");
        }
        BigDecimal b1 = new BigDecimal(Double.valueOf(value1));
        BigDecimal b2 = new BigDecimal(Double.valueOf(value2));
        return b1.divide(b2, scale, BigDecimal.ROUND_HALF_EVEN).toString();
    }

}
